<?php
/**
 * Description: 设置考试项目
 * User: devforma
 * Date: 15/6/7
 * Time: 18:24
 */

class SetExam implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb, $cmsdb;

        if (validateUser($queryArgs) !== 1 || empty($queryArgs['exam_id']) || !is_numeric($queryArgs['exam_id'])) {
            return genOutput(1000);
        }

        //考试项目是否存在
        $examExists = $cmsdb->getVar('SELECT `id` FROM `data_exam_detail` WHERE `id`=:eid',
            array(':eid' => $queryArgs['exam_id']));
        if (empty($examExists))
            return genOutput(1000);

        //获取考试项目和学号
        $userInfo = $uddb->getRow('SELECT `test_id`, `user_sno` FROM `user_social_info` WHERE `user_id`=:uid',
            array(':uid' => $queryArgs['user_id']));

        if (empty($userInfo))
            return genOutput(1000);

        $update = array(
            'test_id' => $queryArgs['exam_id']
        );

        if (empty($userInfo->user_sno)) { //之前没有学号
            $sno = self::genSno($queryArgs['user_id']);
            $update['user_sno'] = $sno;

        } else {
            $sno = $userInfo->user_sno;
        }

        $uddb->update('user_social_info', $update, array('user_id' => $queryArgs['user_id']));

        return genOutput(1, array(
            'sno' => intval($sno)
        ));
    }

    /**
     * 生成用户的学号
     * @param int $userId 用户id
     * @return string 学号
     */
    private static function genSno($userId) {
        return substr(strval(time()), -7).substr('00000'.$userId, -3);
    }
}